package org.jeecg.modules.basic.demo.apartment.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyApartmentCustom;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartmentTreeList;
import org.jeecg.modules.basic.demo.apartment.mapper.LwgyBaseApartmentMapper;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.school.entity.SchoolTreeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


import static org.jeecg.common.util.superSearch.StringComparator.naturalSort;

/**
 * @Description: 学校公寓信息
 * @Author: jeecg-boot
 * @Date: 2020-12-28
 * @Version: V1.0
 */
@Api(tags = "学校公寓信息")
@RestController
@RequestMapping("/apartment/lwgyBaseApartment")
@Slf4j
public class LwgyBaseApartmentController extends JeecgController<LwgyBaseApartment, ILwgyBaseApartmentService> {
    @Autowired
    private ILwgyBaseApartmentService lwgyBaseApartmentService;


    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;
    /**
     * 分页列表查询
     *
     * @param lwgyBaseApartment
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "学校公寓信息-分页列表查询")
    @ApiOperation(value = "学校公寓信息-分页列表查询", notes = "学校公寓信息-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<?> queryPageList(LwgyBaseApartment lwgyBaseApartment,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<LwgyBaseApartment> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseApartment, req.getParameterMap());
            queryWrapper.orderByAsc("name");
            //queryWrapper.orderByAsc("inner_code");

            List<LwgyBaseApartment> list = lwgyBaseApartmentService.queryTreeListNoPage(queryWrapper);
            IPage<LwgyBaseApartment> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = lwgyBaseApartment.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            lwgyBaseApartment.setPid(null);
            QueryWrapper<LwgyBaseApartment> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseApartment, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<LwgyBaseApartment> page = new Page<LwgyBaseApartment>(pageNo, pageSize);
            IPage<LwgyBaseApartment> pageList = lwgyBaseApartmentService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 获取子数据
     *
     * @param lwgyBaseApartment
     * @param req
     * @return
     */
    @AutoLog(value = "学校公寓信息-获取子数据")
    @ApiOperation(value = "学校公寓信息-获取子数据", notes = "学校公寓信息-获取子数据")
    @GetMapping(value = "/childList")
    public Result<?> queryPageList(LwgyBaseApartment lwgyBaseApartment, HttpServletRequest req) {
        QueryWrapper<LwgyBaseApartment> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseApartment, req.getParameterMap());
//        queryWrapper.orderByAsc("inner_code");
        queryWrapper.orderByAsc("name");
        List<LwgyBaseApartment> list = lwgyBaseApartmentService.list(queryWrapper);
        IPage<LwgyBaseApartment> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return
     */
    @AutoLog(value = "学校公寓信息-批量获取子数据")
    @ApiOperation(value = "学校公寓信息-批量获取子数据", notes = "学校公寓信息-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<LwgyBaseApartment> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            queryWrapper.orderByAsc("inner_code");
            List<LwgyBaseApartment> list = lwgyBaseApartmentService.list(queryWrapper);
            IPage<LwgyBaseApartment> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param lwgyBaseApartment
     * @return
     */
    @AutoLog(value = "学校公寓信息-添加")
    @ApiOperation(value = "学校公寓信息-添加", notes = "学校公寓信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LwgyBaseApartment lwgyBaseApartment) {

        lwgyBaseApartment.setLevel(lwgyBaseApartmentService.getLevelByType(lwgyBaseApartment.getType()));
        lwgyBaseApartmentService.addLwgyBaseApartment(lwgyBaseApartment);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param lwgyBaseApartment
     * @return
     */
    @AutoLog(value = "学校公寓信息-编辑")
    @ApiOperation(value = "学校公寓信息-编辑", notes = "学校公寓信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LwgyBaseApartment lwgyBaseApartment) {
        lwgyBaseApartmentService.updateLwgyBaseApartment(lwgyBaseApartment);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param lwgyBaseApartment
     * @return
     */
    @AutoLog(value = "学校公寓信息-编辑")
    @ApiOperation(value = "学校公寓信息-编辑", notes = "学校公寓信息-编辑")
    @PutMapping(value = "/updatePrice")
    public Result<?> updatePrice(@RequestBody LwgyBaseApartment lwgyBaseApartment) {
        lwgyBaseApartmentService.updateBedPrice(lwgyBaseApartment);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "学校公寓信息-通过id删除")
    @ApiOperation(value = "学校公寓信息-通过id删除", notes = "学校公寓信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id,@RequestParam(name = "type", required = false) String type) {
        lwgyBaseApartmentService.deleteLwgyBaseApartment(id,type);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "学校公寓信息-批量删除")
    @ApiOperation(value = "学校公寓信息-批量删除", notes = "学校公寓信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.lwgyBaseApartmentService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "学校公寓信息-通过id查询")
    @ApiOperation(value = "学校公寓信息-通过id查询", notes = "学校公寓信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentService.getById(id);
        if (lwgyBaseApartment == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(lwgyBaseApartment);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param lwgyBaseApartment
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyBaseApartment lwgyBaseApartment) {
        return super.exportXls(request, lwgyBaseApartment, LwgyBaseApartment.class, "学校公寓信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyBaseApartment.class);
    }



    @RequestMapping(value = "/createRoom", method = RequestMethod.POST)
    public Result<?> createRoom(@RequestBody LwgyApartmentCustom lwgyApartmentCustom) {
        if (lwgyApartmentCustom == null) {
            return Result.error("未找到对应数据");
        }
        System.out.println("lwgyApartmentCustom = " + lwgyApartmentCustom.toString());
		String type = lwgyApartmentCustom.getType();
        if("room".equals(type)){
            //创建房间
            lwgyBaseBedService.create_bed(lwgyApartmentCustom);
        }else {
            //创建楼宇
            lwgyBaseApartmentService.everything(lwgyApartmentCustom);
        }
        return Result.OK("成功！");
    }

    @RequestMapping(value = "/copyRoom", method = RequestMethod.POST)
    public Result<?> copyRoom(@RequestBody HashMap<String,Object> map) {
        lwgyBaseApartmentService.copyApartment(map);
        /*map.forEach((key,value)->{
            System.out.println(key  +"==="+ value);
        });*/
        return Result.OK("成功！");
    }


    @RequestMapping("/queryTreeList")
    public Result<List<LwgyBaseApartmentTreeList>>queryTreeList(){
        Result<List<LwgyBaseApartmentTreeList>> result = new Result<>();
//        try {
            List<LwgyBaseApartmentTreeList> list = lwgyBaseApartmentService.queryTreeList(null,null);
            result.setResult(list);
            result.setSuccess(true);
       /* } catch (Exception e) {
            log.error(e.getMessage(),e);
        }*/
        return result;
    }

    @AutoLog(value = "获得打分房间列表")
    @ApiOperation(value="获得打分房间列表", notes="获得打分房间列表")
    @GetMapping("/getFjBaseInfo")
    public Result<?> getFjBaseInfo(){
        List list = lwgyBaseApartmentService.getFjBaseInfo();
        return Result.OK(list);
    }
    @AutoLog(value = "根据Pid获取子节点")
    @ApiOperation(value = "根据Pid获取子节点",notes = "根据pid获取子节点")
    @GetMapping("/getTreeChild")
    public Result<?>getTreeChild(String pid){
        List<LwgyBaseApartment> apartmentList = lwgyBaseApartmentService.getTreeChild(pid);//获取数据
        //直接转为map无法排序
        Map<String, String> apartment = apartmentList.stream()//把list集合转为map
                .collect(Collectors.toMap(LwgyBaseApartment::getName,LwgyBaseApartment::getId));
        List<String> strings = new ArrayList<>(apartmentList.size());
        apartmentList.stream().forEach(apartments->strings.add(apartments.getName()));//取出name进行排序
        long start = System.currentTimeMillis();
        naturalSort(strings);//排序操作
        long end = System.currentTimeMillis();
        log.info("排序用时"+(end-start));
        LwgyBaseApartment lwgyBaseApartment;
        apartmentList.clear();
        for (String name : strings) {
            lwgyBaseApartment = new LwgyBaseApartment();
            lwgyBaseApartment.setName(name);
            lwgyBaseApartment.setId(apartment.get(name));
            apartmentList.add(lwgyBaseApartment);
        }
        return Result.OK(apartmentList);
    }

}
